Lesson 2 - Variables and data types
Variables will get a data type once a value is assigned to them. If a number is assiged to a variable then it is treated as a integer. If text is assigned then it is treated as a string and so on. The code below will fail on the last line as it is trying to add a number and a string together.
x = 10
y = "hello"
z = x + 10
# the next line will fail!
p = y + x
Variables can be given a new data type through simple assignment. Assignment will not only replace the value but also the data type. That means it is perfectly valid to assign a string to a integer variable but not to use it in a calulation. The code below demonstrates this.
x = 10
y = "hello"
z = x + 10
# makes y a integer rather than a string
y = 4
# this line of code is now valid as they are both integers
p = y + z
Python allows you to cast between data types. To cast a variable you must surround it with the short hand name of the type you are converting to. So to convert to a integer you would use int(x) while string would be str(x). The code below shows some examples. Casts will not always work. Words can not be converted to a number in any meaningful way. As such it would cause an error.
x = 10
y = "hello"
z = "81"
# will cause a cast error
p = x + int(y)
# will work fine
p = x + int(z)
# This will print out 1081!
print str(x) + z
# this will print out hello10
print y + str(x)
Key learning points
- A variables data type will be the same as the value it stores
- Assignment can change the data type of a varaible
- Data types must match if they are used in a calculation
- Casting allows you to convert data types
- Casts will always have the variable inside cirlce () brackets